package com.ruoyi.business.youdaoController.shangyou;

import com.ruoyi.business.services.HttpService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ISourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ownXhsApi")
public class XiaoHongShuController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpService httpService;
    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";


    /**
     * http://127.0.0.1:9185/ownXhsApi/send?channelId=7034507403659264&dmpid=1&ts_sec=__ACTION_TIME__&callback_url=http%3a%2f%2f10.215.6.11%3a9185%2fhuidiao%3fa%3d1%26b%3d2&platform=ANDROID&imei_sum=__IMEI_MD5__&oaid=__OAID__&oaid_sum=__OAID_MD5__&mac=__MAC__&ip=__IP__&ua=__UA__
     * @param request
     * @return
     * @throws Exception
     */

    @Log(title = "有道", businessType = BusinessType.ESCALATION, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);
        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");


        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);


        // https://www.xiaohongshu.com/api/sns/v1/ext/ads/CPA-3DSP-N0-{代理商}/clk_collect?ts_sec=__ACTION_TIME__&callback_url=__CALLBACK__&platform=ANDROID&imei_sum=__IMEI_MD5__&oaid=__OAID__
        // &oaid_sum=__OAID_MD5__&mac=__MAC__&ip=__IP__&ua=__UA__


        String idfa = baseParamsMap.get("idfa") + "";
        //如果idfa不为空则，添加idfa_sum字段。 idfa的md5值
        if(StringUtils.isNotBlank(idfa) && !"null".equals(idfa)){
            String idfaSum = DigestUtils.md5DigestAsHex(idfa.getBytes());
            baseParamsMap.put("idfa_sum", idfaSum);
        }
        //oaid和oaid_sum， 如果oaid不为空，并且oaid_sum为空，则添加oaid_sum字段。 oaid的md5值
        String oaid = baseParamsMap.get("oaid") + "";
        String oaidSum = baseParamsMap.get("oaid_sum") + "";
        if(StringUtils.isNotBlank(oaid) && !"null".equals(oaid) && (StringUtils.isBlank(oaidSum) || "null".equals(oaidSum))){
            String oaidSumStr = DigestUtils.md5DigestAsHex(oaid.getBytes());
            baseParamsMap.put("oaid_sum", oaidSumStr);
        }
        //如果有caid字段，没有caid0字段，则添加caid0字段
        String caid = baseParamsMap.get("caid") + "";
        String caid0 = baseParamsMap.get("caid0") + "";
        if(StringUtils.isNotBlank(caid) && !"null".equals(caid) && (StringUtils.isBlank(caid0) || "null".equals(caid0))){
            baseParamsMap.put("caid0", caid);
        }
        //如果有caid字段，没有caid1字段，则添加caid1字段
        String caid1 = baseParamsMap.get("caid1") + "";
        if(StringUtils.isNotBlank(caid) && !"null".equals(caid) && (StringUtils.isBlank(caid1) || "null".equals(caid1))){
            baseParamsMap.put("caid1", caid);
        }

//        //click_id为dmpid
//        baseParamsMap.put("click_id", dmpid);
//        //is_imp 为true
//        baseParamsMap.put("is_imp", true);
//        //osv	可选	string	系统版本号
//        //boot_time	可选	string	ios 启动时间
//        //system_update_time	可选	string	ios 更新时间
//        //给出上面上个参数
//        baseParamsMap.put("osv", "14.0.1");
//        //boot_time随机当前年月的某天
//        baseParamsMap.put("boot_time", URLEncoder.encode(randomTime(), Constants.UTF8));
//        baseParamsMap.put("system_update_time", URLEncoder.encode( randomTime(), Constants.UTF8));
//        //android_id_sum 给出一个随机uuid的md5值
//        baseParamsMap.put("android_id_sum", DigestUtils.md5DigestAsHex(IdUtils.fastUUID().getBytes()));


        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){
            ua = URLDecoder.decode(ua, Constants.UTF8);
        }else{
            //request 获取 ua  -20240829 ppj 标识不需要ua
//            ua = request.getHeader("User-Agent");
//            baseParamsMap.put("ua", URLEncoder.encode(ua, Constants.UTF8));
        }
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){
        }else{
            //request 获取 ip
//            ip = IpUtils.getIpAddr(request);
        }

        String callbackUrl = URLDecoder.decode(baseParamsMap.get("callback_url") + "", Constants.UTF8);
        String callbackRequestAddress = GetUrlParam.getRequestAddress(callbackUrl);
        String callbackStaticParameters = GetUrlParam.TruncateUrlPage(callbackUrl);
        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownXhsApi/callback/"+ channelId +"/"+ dmpid +"/";
        callbackBase = "https://www.ssptqt.com/ownXhsApi/callback/"+ channelId +"/"+ dmpid +"/";
        String encrypt_u = encrypDES.encrypt(callbackRequestAddress);


        //callbackStaticParameters去除&event_type=__EVENT__参数
        callbackStaticParameters = callbackStaticParameters.replace("&event_type=__EVENT__", "");
        String nu = callbackBase + encrypt_u + "?"+callbackStaticParameters;


        //小红书回调地址取得参数是callback_url
        baseParamsMap.put("callback_url", URLEncoder.encode(nu, Constants.UTF8));
        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMap.keySet()){
            tempList.add(key+"="+baseParamsMap.get(key));
        }
        String requestParameters = String.join("&", tempList);


        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "click";
        if("POST".equals(requestType)){
            httpService.sendPost(requestAddress, requestParameters, ip, ua, uuid, reqType);
        }else{
            httpService.sendGet(requestAddress, requestParameters, ip, ua, uuid, reqType);
        }

        redisCache.setCacheMapValue(dmpid+"_Cache", "requestAddress", requestAddress);
        redisCache.setCacheMapValue(dmpid+"_Cache", "requestParameters", requestParameters);
        redisCache.setCacheMapValue(dmpid+"_Cache", "reqResultId", uuid);
        return R.success().msg(uuid);
    }

    @Log(title = "有道", businessType = BusinessType.CALLBACK, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object send(HttpServletRequest request, @PathVariable("channelId") String channelId, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        String queryString = request.getQueryString();
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);

        //获取请求参数, 并替换属性
        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "callback";
        httpService.sendGet(requestAddress, queryString, null, null, uuid, reqType);
        return R.success().msg(uuid);
    }


    public static String randomTime(String... specifyYear) {
        //获取当前年月
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        //补0
        String monthStr = month < 10 ? "0" + month : month + "";
        //当前日
        int currday = calendar.get(Calendar.DAY_OF_MONTH);
        //随机天数
        int randomDay = (int) (Math.random() * currday);
        //补0
        String randomDayStr = randomDay < 10 ? "0" + randomDay : randomDay + "";
        //随机时间
        int randomHour = (int) (Math.random() * 24);
        int randomMinute = (int) (Math.random() * 60);
        int randomSecond = (int) (Math.random() * 60);
        //上面的三个参数补0
        String randomHourStr = randomHour < 10 ? "0" + randomHour : randomHour + "";
        String randomMinuteStr = randomMinute < 10 ? "0" + randomMinute : randomMinute + "";
        String randomSecondStr = randomSecond < 10 ? "0" + randomSecond : randomSecond + "";
        return year + "-" + monthStr + "-" + randomDayStr + " " + randomHourStr + ":" + randomMinuteStr + ":" + randomSecondStr;
    }


    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(randomTime());
        }
    }

}
